// 渲染不同类型的组件
const formType = "render";

const renderComponent = (config) => {
    if (!config?.type) return 'div';
    if (config.isCustomWidget) {
        return 'CustomWidget';
    }
    const typeName = config.type.charAt(0).toUpperCase() + config.type.slice(1);
    if (config.isContainer) return `${typeName}Render`;
    return `${typeName}Widget`;
};

const getFormFieldData = (list, formData) => {
    for (let i = list.length - 1; i >= 0; i--) {
        const item = list[i];
        if (item.fieldId && formData.hasOwnProperty(item.id)) {
            formData[item.fieldId] = formData[item.id];
            delete formData[item.id]; // 删除旧的 key
            // 如果是子表单，递归处理每一项
            if (item.isSubForm && Array.isArray(formData[item.fieldId])) {
                formData[item.fieldId] = formData[item.fieldId].map(child =>
                    getFormFieldData(item.children, child)
                );
            }
        }
        if (item.children && item.children.length > 0 && !item.isSubForm) {
            getFormFieldData(item.children, formData);
        }
    }
    return formData;
};

const getFormIdData = (list, formData) => {
    for (let i = list.length - 1; i >= 0; i--) {
        const item = list[i];
        if (item.fieldId && formData.hasOwnProperty(item.fieldId)) {
            formData[item.id] = formData[item.fieldId];
            delete formData[item.fieldId]; // 删除旧的 key
            // 如果是子表单，递归处理每一项
            if (item.isSubForm && Array.isArray(formData[item.id])) {
                formData[item.id] = formData[item.id].map(child =>
                    getFormIdData(item.children, child)
                );
            }
        }
        if (item.children && item.children.length > 0 && !item.isSubForm) {
            getFormIdData(item.children, formData);
        }
    }
    return formData;
};

const checkSubFormData = (list, formData, formNames = []) => {
    for (let i = list.length - 1; i >= 0; i--) {
        const item = list[i];
        // 子表单且必填
        if (item.isSubForm && item?.attributes?.required) {
            const subFormData = formData?.[item.id];
            if (!Array.isArray(subFormData) || subFormData.length === 0) {
                formNames.push(item?.attributes?.label || item.id);
            }
        }
        // 递归检查子项
        if (item.children && item.children.length > 0) {
            checkSubFormData(item.children, formData, formNames);
        }
    }
    return formNames;
};

export default {
    formType,
    checkSubFormData,
    getFormIdData,
    getFormFieldData,
    renderComponent,
}